package com.shopping.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import com.shopping.bean.Review;
import com.shopping.dao.ReviewDao;
import com.shopping.util.DBUtil;

public class ReviewDaoImpl implements ReviewDao {

	JdbcTemplate jt = new JdbcTemplate(DBUtil.getDataSource());
	@Override
	public List<Review> selectAll(Map<String, String[]> condition) {
		String sql = "select * from review where 1=1 ";
		int pageNum = 1;
		int pageSize = 5;
		
		List list = new ArrayList();
		for(String key:condition.keySet()) {
			if("keyword".equals(key) && !"".equals(condition.get(key)[0])) {
				sql += "or goodsId = ? ";
				list.add("%"+condition.get(key)[0]+"%");
			}
			
			if("keyword".equals(key) && !"".equals(condition.get(key)[0])) {
				sql += "or userId = ? ";
				list.add("%"+condition.get(key)[0]+"%");
			}
			
		}
		try {
			pageNum = Integer.parseInt(condition.get("pageNum")[0]);
		}catch(Exception e) {
			
		}
		try {
			pageSize = Integer.parseInt(condition.get("pageSize")[0]);
		}catch(Exception e) {
			
		}
		sql += "LIMIT ?,?";
		list.add((pageNum-1)*pageSize);
		list.add(pageSize);
		
		List<Review> goods = jt.query(sql, new BeanPropertyRowMapper<Review>(Review.class),list.toArray());
		return goods;
	}
	@Override
	public int selectTotalRows(Map<String, String[]> condition) {
		String sql ="SELECT count(1) FROM review WHERE 1 = 1 ";
		List params = new ArrayList();
		for(String key: condition.keySet()) {
			if("keyword".equals(key) && !"".equals(condition.get(key)[0])) {
				sql += "or goodsId = ? ";
				params.add(condition.get(key)[0]);
			}
			if("keyword".equals(key) && !"".equals(condition.get(key)[0])) {
				sql += "or userId = ? ";
				params.add("%"+condition.get(key)[0]+"%");
			}
			
		}
		
			return jt.queryForObject(sql, Integer.class,params.toArray());
	}

}
